﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using FlashcardPdfCreator;
using System.IO;
using FlashcardWeb.Models;
using System.Text;
using System.Web.Hosting;
using UsefulCode;

namespace FlashcardWeb.Controllers
{
    public class FileController : Controller
    {
		private static readonly FlashcardFonts fonts = new FlashcardFonts(Path.Combine(HostingEnvironment.MapPath("~/App_Data"), "arial.ttf"));

		//public ActionResult UploadCsv()
		//{
		//    try
		//    {
		//        if (Request.Files.Count == 1 && Request.Files[0].ContentLength > 0)
		//        {
		//            MemoryStream downloadStream;
		//            string fileName;

		//            using (MemoryStream uploadedStream = new MemoryStream())
		//            {
		//                Request.Files[0].InputStream.CopyTo(uploadedStream);
		//                fileName = Path.GetFileNameWithoutExtension(Request.Files[0].FileName);
		//                uploadedStream.Position = 0;

		//                using (CsvStreamReaderCardDataProvider provider = new CsvStreamReaderCardDataProvider(uploadedStream))
		//                {

		//                    Creator creator = new Creator();
		//                    downloadStream = creator.CreatePdf(provider.GetCardData, fonts);
		//                }
		//            }

		//            downloadStream.Position = 0;

		//            return new FileStreamResult(downloadStream, "application/pdf")
		//            {
		//                FileDownloadName = fileName + "_flashcard.pdf"
		//            };
		//        }
		//    }
		//    catch (Exception exception)
		//    {
		//        ModelState.AddModelError("", exception.Message + exception.StackTrace + (exception.InnerException != null ? exception.InnerException.Message + exception.InnerException.StackTrace : string.Empty));
		//    }


		//    return View("Index");
		//}

		public ActionResult Test()
		{
			string file = Db.GetConnectioString("pronunciation");
			var resu = System.IO.Directory.GetFiles(Path.GetDirectoryName(file));

			return Json(resu, JsonRequestBehavior.AllowGet);
		}





		public ActionResult UploadCsvFile(char separator)
		{
			try
			{
				ICardData[] data = null;

				foreach (string inputTagName in Request.Files)
				{
					if (Request.Files.Count == 1 && Request.Files[0].ContentLength > 0)
					{
						

						using (MemoryStream uploadedStream = new MemoryStream())
						{
							Request.Files[0].InputStream.CopyTo(uploadedStream);
							uploadedStream.Position = 0;

							using (CsvStreamReaderCardDataProvider provider = new CsvStreamReaderCardDataProvider(uploadedStream))
							{
								data = provider.GetCardData(separator).ToArray();
							}
						}

						

					}
				}
				return View("updateLocalStorage", data);
			}
			catch (Exception exception)
			{
				ModelState.AddModelError("", exception.Message + exception.StackTrace + (exception.InnerException != null ? exception.InnerException.Message + exception.InnerException.StackTrace : string.Empty));
			}


			return View("updateLocalStorage", null);
		}


		public ActionResult GetJsonFile(Flashcard[] cards)
		{
			return View(cards);
		}

		public ActionResult GetCsvFile(Flashcard[] cards)
		{
			if (cards.Length > 0)
			{
				MemoryStream ms = new MemoryStream();
				StreamWriter streamWriter = new StreamWriter(ms, Encoding.Unicode);

				foreach (Flashcard card in cards)
				{
					streamWriter.WriteLine(string.Format(
								   "\"{0}\";\"{1}\";\"{2}\";\"{3}\";\"{4}\"",
								   card.Word,
								   card.Pronunciation,
								   card.Example,
								   card.Meaning,
								   card.Translation));
				}

				streamWriter.Flush();
				ms.Seek(0, SeekOrigin.Begin);

				return new FileStreamResult(ms, "application/octet-stream")
				{
					FileDownloadName = "flashcard.csv"
				};
			}

			return View("Index");
		}

		public ActionResult ProcessForm(Flashcard[] cards)
		{
			if (cards.Length > 0)
			{
				MemoryStream downloadStream = null;

				Func<IEnumerable<ICardData>> getCardData = () =>
				{
					return cards.AsEnumerable();
				};

				Creator creator = new Creator();
				downloadStream = creator.CreatePdf(getCardData, fonts);

				return new FileStreamResult(downloadStream, "application/pdf")
				{
					FileDownloadName = "flashcard.pdf"
				};
			}

			return View("Index");
		}
    }
}
